from datetime import datetime
import random
import re

from flask import json, session
from flask import jsonify

from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.response_code import RET
from . import passport_blu
from flask import request
from flask import abort
from flask import current_app
from flask import make_response

from info import redis_store, db
from info import constants
from info.utils.captcha.captcha import captcha

@passport_blu.route("/logout")
def logout():
    session.pop('user_id', None)
    session.pop('mobile', None)
    session.pop('nick_name', None)

    session.pop('is_admin', None)

    return jsonify(errno=RET.OK, errmsg="退出成功")

@passport_blu.route("/login",methods=["POST"])
def login():
    params_dict=request.json
    mobile=params_dict.get("mobile")
    passport=params_dict.get("passport")
    if not all([mobile,passport]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号码格式不正确")
    try:
        user=User.query.filter(User.mobile == mobile).first()
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    if not user.check_password(passport):
        return jsonify(errno=RET.PWDERR, errmsg="用户用户名或密码错误")

    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    user.last_login = datetime.now()
    # try:
    #     db.session.commit()
    # except Exception as ret:
    #     db.session.rollback()
    #     current_app.logger.error(ret)

    return jsonify(errno=RET.OK, errmsg="登录成功")



@passport_blu.route("/register",methods=["POST"])
def register():
    param_dict=request.json
    mobile = param_dict.get("mobile")
    smscode = param_dict.get("smscode")
    password = param_dict.get("password")
    if not all([mobile,smscode,password]):
        print([mobile,smscode,password])
        return jsonify(errno=RET.PARAMERR, errmsg="参数")
    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号码格式不正确")
    try:
        real_sms_code=redis_store.get("SMS_" + mobile)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")
    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")

    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    user.last_login=datetime.now()
    user.password=password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as ret:
        current_app.logger.error(ret)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name

    # 7. 返回响应
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_blu.route("/sms_code",methods=["POST"])
def send_sms_code():
    '{"mobiel": "18811111111", "image_code": "AAAA", "image_code_id": "u23jksdhjfkjh2jh4jhdsj"}'
    params_dict=request.json
    mobile = params_dict.get("mobile")
    image_code = params_dict.get("image_code")
    image_code_id = params_dict.get("image_code_id")

    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数有误")

    if not re.match('1[35678]\\d{9}',mobile):
        return jsonify(errno=RET.PARAMERR,errmsg="手机号码格式不正确")
    try:
        real_image_code = redis_store.get("ImageCodeId_"+image_code_id)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR,errmsg="数据查询失败")
    if not real_image_code:
        return jsonify(errno=RET.NODATA,errmsg="图片验证码过期")

    if real_image_code.upper()!= image_code.upper():
        return jsonify(errno=RET.DATAERR,errmsg="图片验证码输入错误")

    sms_code_str="%06d" %random.randint(0,999999)
    current_app.logger.debug("短信验证码内容是：%s"% sms_code_str)
    # result=CCP().send_template_sms(mobile,[sms_code_str,constants.SMS_CODE_REDIS_EXPIRES/5],"1")
    # if result !=0:
    #     return jsonify(errno=RET.THIRDERR,errmsg="发送短信失败")
    try:
        redis_store.set("SMS_"+mobile,sms_code_str,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as ret:
        current_app.logger.error(ret)
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route('/image_code')
def get_image_code():
    image_code_id = request.args.get("imageCodeId",None)


    if not image_code_id:
        return abort(403)
    name, text, image = captcha.generate_captcha()

    try:
        redis_store.set("ImageCodeId_" + image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
    except Exception as ret:
        current_app.logger.error(ret)
        abort(500)
    response = make_response(image)
    # 设置数据的类型，以便浏览器更加智能识别其是什么类型
    response.headers["Content-Type"] = "image/jpg"
    return response